#！/usr/bin/env python
# -*- coding:utf-8 -*-

#
from tkinter import *
from tkinter import ttk
# from lib.core.Spider import SpiderMain
# import hashlib
import threading
import time
import os

import requests
from urllib3.exceptions import MaxRetryError

LOG_LINE_NUM = 0

patten = r'https://stickershop.line-scdn.net/stickershop/v1/sticker/\d+/android/sticker.png'
target_url = 'https://store.line.me/stickershop/product/14308849/zh-Hans'


header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.3'
}

pre_target_url = 'https://stickershop.line-scdn.net/stickershop/v1/sticker/{}/android/sticker.png'

def get_str_from_url(url: str) -> str:
    """

    :param url: web url
    :return: saw string to be marched
    """
    response = requests.get(url, headers=header)
    return str(response.content)


def tin_url_list(url_list: list) -> (list, int, int):
    """
    This function will be refactor in next
    :param url_list: full pic url
    :return: formatted data
    """
    temp = []
    # first = 0
    pattern4findfirst = r'/\d+'

    for li in url_list:
        if li not in temp:
            temp.append(li)
    t = re.findall(pattern4findfirst, url_list[0])
    first = int(t[0][1:])
    # print(url_list[0].split(str(first)))
    print('Have found {} pictures'.format(len(temp)))

    return temp, first, len(temp)


def get_from_num(num) -> bool:
    """

    :param num: number of pic
    :return: flag shows this pic if saved successfully
    """
    target_url = pre_target_url.format(str(num))
    try:
        pic_data = requests.get(target_url, headers=header)
        with open('./arc/{}.png'.format(str(num)), 'wb+') as pic_file:
            pic_file.write(pic_data.content)
            print('pic_{}.png have been saved!\n'.format(str(num)))
            pic_data.close()
        return True
    except TimeoutError as ex:
        return False
    except MaxRetryError as ex:
        return False
    except requests.exceptions.ConnectionError as ex:
        return False


class MY_GUI():
    def __init__(self,init_window_name):
        self.init_window_name = init_window_name


    #设置窗口
    def set_init_window(self):
        self.init_window_name.title("LINE")   # 窗口名
        self.init_window_name.geometry('900x740+10+10')   # 900x740为窗口大小，+10 +10 定义窗口弹出时的默认展示位置
        self.init_window_name["bg"] = "Azure"  # 窗口背景色，其他背景色见：blog.csdn.net/chl0000/article/details/7657887
        # self.init_window_name.attributes("-alpha",0.9)  # 虚化，值越小虚化程度越高
        # 上部分的frame
        self.input_frame = Frame(self.init_window_name, width=800, height=60, relief="ridge", borderwidth=5)
        # 输入标签
        self.input_label = Label(self.input_frame, text='网址: ', font=('楷体', 16), relief="ridge", anchor=CENTER)
        self.input_label.place(relx=0.05, rely=0.3, relwidth=0.1)
        self.input = StringVar()
        self.input.set('https://store.line.me/stickershop/product/14308849/zh-Hans')
        # 输入框
        self.input_entry = Entry(self.input_frame, textvariable=self.input, font="Helvetica 16")
        self.input_entry.place(relx=0.16, rely=0.3, relwidth=0.59)
        # 运行按钮
        self.run = PhotoImage(file="./Run.png")
        self.func_run = Button(self.input_frame, image=self.run, command=lambda: self.click_all_pic() , bg="lightblue", text="运行（RUN）",font=('楷体', 15), compound=RIGHT)
        self.func_run.place(relx=0.76, rely=0.3, relwidth=0.2)
        self.input_frame.pack(padx=10, pady=5)
        # 下部分的frame
        self.exc_frame = Frame(self.init_window_name, width=800, height=640, relief="ridge", borderwidth=5)
        # 显示运行过程的文本框
        self.result = Text(self.exc_frame,font=(10), relief="ridge")
        yscrollbar = Scrollbar(self.result)
        yscrollbar.pack(side=RIGHT,fill=Y)
        self.result.place(relx=0.05, rely=0.05, relwidth=0.9, relheight=0.8)
        # self.result.insert(END,"test")
        yscrollbar.config(command=self.result.yview)
        self.result.config(yscrollcommand=yscrollbar.set)
        self.exc_frame.pack(padx=10, pady=5)

        # 获取当前时间
    def get_current_time(self):
        current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        return current_time

    def click_all_pic(self):
        target_url=self.input.get()
        res = re.findall(patten, get_str_from_url(target_url))
        url_list, first, length = tin_url_list(res)
        if not os.path.exists('arc'):
            os.mkdir('arc')
        for i in range(first, first + length):
            tr = threading.Thread(target=get_from_num, args=(i,))
            tr.start()






